package com.example.librarymanagement.service.impl;

import com.example.librarymanagement.mapper.UserMapper;
import com.example.librarymanagement.model.User;
import com.example.librarymanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public boolean registerUser(User user) {
        // 这里可以添加更多的业务逻辑，比如检查用户名是否已存在
        return userMapper.insertUser(user) > 0;
    }
    @Override
    public boolean authenticateUser(String username, String password) {
        User user = userMapper.findUserByUsernameAndPassword(username, password);
        return user != null;
    }
    @Override
    public User updateUser(Integer id, User user) {
        int updatedRows = userMapper.update(id, user.getUsername(), user.getPassword());
        if (updatedRows > 0) {
            return userMapper.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
        }
        return null;
    }
    @Override
    public User getUserByUsername(String username) {
        // 使用 Optional 获取用户，如果不存在则抛出异常或返回 null
        return userMapper.getUserByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found with username: " + username));
    }
    public boolean isUsernameExists(String username) {
        return userMapper.isUsernameExists(username);
    }
    @Override
    public List<User> findAllUsers() {
        return userMapper.findAllUsers();
    }
}